﻿using PLC.Application.Groups.Services;
using PLC.Application.Variables.Services;
using PLC.Interface.Groups;
using PLC.Interface.Variables;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using YWM;
using YWM.Dto;

namespace PLC.Application.Groups
{
    public class GroupAppService : IGroupAppService
    {
        private readonly IGroupService _groupService = YApp.Resolve<IGroupService>();

        private readonly IVariableService _variableService = YApp.Resolve<IVariableService>();

        public async Task<IReadOnlyList<GroupResultDto>> GetList(bool isLoadVariables)
        {
            PagedResultDto<GroupResultDto> pagedResultDto = await _groupService.GetAll(new GroupResultRequestDto());
            IReadOnlyList<GroupResultDto> list = pagedResultDto.Items;
            if (isLoadVariables)
            {
                PagedResultDto<VariableResultDto> variablePagedResultDto = await _variableService.GetAll(new VariableResultRequestDto { MaxResultCount = int.MaxValue });
                foreach (GroupResultDto group in list)
                {
                    group.Variables = variablePagedResultDto.Items.Where(v => v.GroupId == group.Id).ToList();
                }
            }
            return list;
        }

        public Task<GroupResultDto> Save(GroupDto input)
        {
            return input.Id > 0 ? _groupService.Update(input) : _groupService.Create(input);
        }

        public Task Delete(EntityDto input)
        {
            return _groupService.Delete(input);
        }
    }
}
